Ext.onReady(function(){
	var store = new Ext.data.Store({
		proxy: new Ext.ux.data.PagingMemoryProxy(data),
		reader: new Ext.data.ArrayReader({
			record: 'list',
			id: 'Id',
			totalRecords: '@total'
		}, [{
			name: 'Id'
		}, {
			name: 'name'
		}, {
			name: 'price',
			type: 'float'
		}, {
			name: 'bprice',
			type: 'float'
		}, {
			name: 'sort'
		}, {
			name: 'eatery'
		}, {
			name: 'image'
		}])
	});

	    function chMoney(val){
            return '<span style="color:red;">' + val + '￥</span>';
    }

	    function dishImage(value){
        return String.format(
                '<b></b><img src="image/dish/{0}" width="60" height="40">',
                value);
    }
	
	    function onDelete() {
        var rec = secondGrid.getSelectionModel().getSelected();
        if (!rec) {
            return false;
        }
        secondGrid.store.remove(rec);
    }

    Ext.ux.grid.GroupSummary.Calculations['totalCost'] = function(v, record, field){
        return v + (record.data.estimate * record.data.rate);
    };
	
	var summary = new Ext.ux.grid.GroupSummary();

    var grid = new Ext.grid.GridPanel({
        store: store,
		ddGroup          : 'secondGridDDGroup',
		enableDragDrop   : true,
		ddText :'选择了一道菜',
		autoExpandColumn : 'name',
		loadMask         : true,
		width:480,
        columns: [
            {header: "名称", width: 180, dataIndex: 'name', sortable: true},
            {header: "单价", width: 80,renderer:chMoney, dataIndex: 'price', sortable: true},
            {header: "餐馆", width: 115, dataIndex: 'eatery', sortable: true},
            {header: "图片", width: 100, dataIndex: 'image',renderer:dishImage, sortable: false}
        ],
		sm: new Ext.grid.RowSelectionModel({singleSelect: true}),
		viewConfig: {
			forceFit: true,
                sortAscText :'正序',
                sortDescText :'倒序',
                columnsText:'列显示/隐藏',
                groupByText:'依本列分组',
                showGroupsText:'分组显示',
                groupTextTpl: '{text} ({[values.rs.length]} 条记录)'
		},
        height:400,
		split: true,
		region: 'east'
    });
	var bookTplMarkup = [
		'<img src="image/dish/{image}" width="230" height="150">',
		'菜名: <b>{name}</b><br/>',
		'提供餐馆: {eatery}<br/>',
		'<div id="myList" style="width:300px;height:200px;background-color: #000000;"></div>'
	];
	var bookTpl = new Ext.Template(bookTplMarkup);

	var fields = [
	   {name: 'name', mapping : 'name'},
	   {name: 'image', mapping : 'image',id :'image'},
	   {name: 'column2', mapping : 'column2'}
	];

    var secondGridStore = new Ext.data.JsonStore({
        fields : fields,
		root   : 'records'
    });

    var secondGrid = new Ext.grid.GridPanel({
	ddGroup          : 'grid',
        store            : secondGridStore,
		sortInfo: {field: 'due', direction: 'ASC'},
        columns          : [
		{ id : 'name', header: "Record Name", width: 160, sortable: true, dataIndex: 'name'},
		{header: "price",id:"price", width: 50, sortable: true, dataIndex: 'price',summaryType: 'sum',renderer: function(value, metadata, record, rowIndex, colIndex, store) {  
var obj = record.data;  
return value + obj.price;
}
},
					{header:"结果",width:50,sortable: true,summaryType: 'sum', dataIndex: 'column2',                renderer : function(v){
                    return v ;
                }
            }
	],
	enableDragDrop   : true,
        stripeRows       : true,
        autoExpandColumn : 'name',
        width            : 325,
		height:400,
	region           : 'center',
        title            : 'Second Grid',
		bbar    : [
			'->', // Fill
			{
				text    : 'Reset both grids',
				handler : function() {
Ext.Ajax.request({
   url: 'book.php',
	success: function ( result, request ) { 
		Ext.MessageBox.alert('Success', 'Data return from the server: '+ result.responseText); 
		//alert(typeof(secondGridStore.data.items[0]) ); //显示[object]
		//alert(secondGridStore.data.items[0].constructor ); //显示function () {H.apply(this, arguments);}
		//alert(loadRecord(secondGrid.getSelectionModel().getSelections()));
		
	},
	failure: function ( result, request) { 
		Ext.MessageBox.alert('Failed', result.responseText); 
	},
   headers: {
       'my-header': 'foo'
   },
   params: { 
   foo: list,
   test : secondGridStore.data.items.length,
   action : secondGridStore.data.innerHTML }
});
					
				//secondGridStore.getForm().getEl().dom.action = 'include/User/login.php';
                //secondGridStore.getForm().getEl().dom.method = 'POST';   
                //secondGridStore.getForm().submit();   
				}
			}
		],
		tbar    : 
		[{
            text: 'Add',
            iconCls: 'silk-add',
            handler: onDelete
        }, '-', {
            text: 'Delete',
            iconCls: 'silk-delete',
            handler: onDelete
        }, '-', // Fill
			{
				text    : 'Reset both grids',
				handler : function() {
					alert(secondGridStore.data.items);
					secondGridStore.removeAll();
				}
			}
		]

    });


	var ct = new Ext.Panel({
		renderTo: 'mainDiv',
		frame: true,
		split: true,
		collapsible: true,
		width: 740,
		height: 400,
		layout: 'border',
		items: [
			grid,
			{
				id: 'detailPanel',
				region: 'center',
				bodyStyle: {
					background: '#ffffff',
					padding: '7px'
				},
				html: '选择查看详情.<div id="myList" style="width:300px;height:200px;background-color: #000000;"></div>'
			}
		],
				bbar: new Ext.PagingToolbar({
            pageSize: 5,
            store: store,
            displayInfo: true,
            plugins: new Ext.ux.ProgressBarPager()
        })
	})
	grid.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {
		var detailPanel = Ext.getCmp('detailPanel');
		bookTpl.overwrite(detailPanel.body, r.data);
	});
    //store.load();
	store.load({params:{start:0, limit:5}});
	secondGrid.render('sg');
	

	
		var firstGridDropTargetEl =  grid.getView().el.dom.childNodes[0].childNodes[1];
	var firstGridDropTarget = new Ext.dd.DropTarget(firstGridDropTargetEl, {
		ddGroup    : 'firstGridDDGroup',
		copy       : true,
		notifyDrop : function(ddSource, e, data){

			// Generic function to add records.
			function addRow(record, index, allItems) {

				// Search for duplicates
				var foundItem = firstGridStore.findExact('name', record.data.name);
				// if not found
				if (foundItem  == -1) {
					firstGridStore.add(record);

					// Call a sort dynamically
					firstGridStore.sort('name', 'ASC');

					//Remove Record from the source
					ddSource.grid.store.remove(record);
				}
			}

			// Loop through the selections
			Ext.each(ddSource.dragData.selections ,addRow);
			return(true);
		}
	});


	// This will make sure we only drop to the view container
	var secondGridDropTargetEl = secondGrid.getView().el.dom.childNodes[0].childNodes[1]

	var destGridDropTarget = new Ext.dd.DropTarget(secondGridDropTargetEl, {
		ddGroup    : 'secondGridDDGroup',
		copy       : false,
		notifyDrop : function(ddSource, e, data){

			// Generic function to add records.
			function addRow(record, index, allItems) {

				// Search for duplicates
				var foundItem = secondGridStore.findExact('name', record.data.name);
				// if not found
				if (foundItem  == -1) {
					secondGridStore.add(record);
					// Call a sort dynamically
					secondGridStore.sort('name', 'ASC');

					//拖动之后是否删除
					//ddSource.grid.store.remove(record);
				}
			}
			// Loop through the selections
			Ext.each(ddSource.dragData.selections ,addRow);
			return(true);
		}
	});
		
	
});